/**
 *
 */
package com.zhuoyue.zhtj.service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.eit.eitsite.common.utils.HttpUtils;
import com.eit.eitsite.common.utils.IdGen;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhuoyue.elmt.utils.GsonUtils;
import com.zhuoyue.zhtj.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eit.eitsite.common.persistence.Page;
import com.eit.eitsite.common.service.CrudService;
import com.zhuoyue.zhtj.dao.KckqjlDao;

/**
 * 考勤记录Service
 *
 * @author hss
 * @version 2017-09-22
 */
@Service
@Transactional(readOnly = true)
public class KckqjlService extends CrudService<KckqjlDao, Kckqjl> {
    @Autowired
    private KckqjlDao kckqjlDao;

    public Kckqjl get(String id) {
        return super.get(id);
    }

    public List<Kckqjl> findList(Kckqjl kckqjl) {
        return super.findList(kckqjl);
    }

    public Page<Kckqjl> findPage(Page<Kckqjl> page, Kckqjl kckqjl) {
        return super.findPage(page, kckqjl);
    }

    @Transactional(readOnly = false)
    public void save(Kckqjl kckqjl) {
        super.save(kckqjl);
    }

    @Transactional(readOnly = false)
    public void delete(Kckqjl kckqjl) {
        super.delete(kckqjl);
    }

    /**
     * 计算某类课程总周次
     *
     * @param zc
     * @return
     */
    public int getTotalZc(String zc) {
        int num = 0;
        String zcTem = zc.replace("周", "");
        //形如3-16,19-20
        if (zcTem.indexOf("，") != -1) {
            zcTem = zcTem.replace("，", ",");
        }
        if (zcTem.indexOf(",") != -1) {
            String[] temp1 = zcTem.split(",");
            int[] num2 = new int[temp1.length];
            int total = 0;
            for (int i = 0; i < temp1.length; i++) {
                if (temp1[i].indexOf("-") != -1) {
                    String[] temp2 = temp1[i].split("-");
                    num2[i] = Integer.parseInt(temp2[1].trim()) - Integer.parseInt(temp2[0].trim()) + 1;
                    total += num2[i];
                } else {
                    num2[i] = 1;
                    total += num2[i];
                }
            }
            return total;
        }
        //形如3-16
        if (zcTem.indexOf("-") != -1) {
            String[] temp1 = zcTem.split("-");
            return Integer.parseInt(temp1[1].trim()) - Integer.parseInt(temp1[0].trim()) + 1;
        }
        return num + 1;
    }

    /**
     * 获取课程小节数
     *
     * @param jc
     * @return
     */
    private int getJc(String jc) {
        jc = jc.replace("节", "");
        if (jc.indexOf("，") != -1) {
            jc.replace("，", ",");
        }
        return jc.split(",").length;
    }

    /**
     * 获取本学期课程名称及总周次
     *
     * @param course
     * @return
     */
    public Map<String, Object> getCourseZcInfo(Course[] course) {
        Map<String, Object> map = Maps.newHashMap();
        for (Course courseItem : course) {
            if (!map.containsKey(courseItem.getKcmc())) {
                map.put(courseItem.getKcmc(), getTotalZc(courseItem.getZc()));
            }
        }
        return map;
    }

    /**
     * 获取一周各个课程节次及总节次
     *
     * @param course
     * @return
     */
    public Map<String, List<CourseXqJc>> getCourseJcInfo(Course[] course) {
        Map<String, List<CourseXqJc>> map1 = Maps.newHashMap();
        for (Course courseItem : course) {
            List<CourseXqJc> list = Lists.newArrayList();
            CourseJc courseJc = new CourseJc(courseItem.getJc(), getJc(courseItem.getJc()));
            CourseXqJc courseXqJc = new CourseXqJc(courseItem.getXq(), courseJc);
            list.add(courseXqJc);
            if (!map1.containsKey(courseItem.getKcmc())) {
                map1.put(courseItem.getKcmc(), list);
            } else {
                map1.get(courseItem.getKcmc()).add(courseXqJc);
            }
        }
        return map1;
    }

    @Transactional(readOnly = false)
    public Map<String, Object> getCourse(Kckqjl kckqjl) {
        String course = HttpUtils.httpStrGet("http://student.szpt.edu.cn/classroom/index.php/UserApi/getCourse?num=" + kckqjl.getNumber() + "&xn=" + kckqjl.getSemeyear() + "&xq=" + kckqjl.getSemester());
        if (course != null) {
            if(kckqjlDao.selectInfoByKckqjl(kckqjl)==null){
                kckqjl.setCourseinfo(course);
                kckqjl.setId(IdGen.uuid());
                kckqjlDao.insert(kckqjl);
            }
            Course[] studentCourse = GsonUtils.newInstance().fromJson(course, Course[].class);
            List<String> list = Lists.newArrayList();
            //获取所有课程名称
            if (studentCourse != null) {
                for (int i = 0; i < studentCourse.length; i++) {
                    String courseName = studentCourse[i].getKcmc();
                    if (!list.contains(courseName)) {
                        list.add(courseName);
                    }
                }
            }
            Map<String, Object> map = getCourseZcInfo(studentCourse);
            Map<String, List<CourseXqJc>> maps = getCourseJcInfo(studentCourse);
            //每一轮循环代表一种课
            int total = 0;
            for (int i = 0; i < map.size(); i++) {
                int zc =(int) map.get(list.get(i));
                int js = 0;
                List<CourseXqJc> courseList = maps.get(list.get(i));
                for (int j = 0; j < courseList.size(); j++) {
                    js += courseList.get(j).getCourseJc().getJs();
                }
                map.put(list.get(i), zc * js);
                total += zc * js;
            }
            map.put("all", total);
            return map;
        }
        return null;
    }

    @Transactional(readOnly = false)
    public boolean saveRecord(String str) {
        try {
            str = URLDecoder.decode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] kqinfo = str.split("&amp;");
        List<Kqjl> list = assembleKqjl(kqinfo);
        if (list != null && list.size() > 0) {
            int row = kckqjlDao.insertKqjl(list);
            if (row == list.size()) {
                return true;
            }
        }
        return false;
    }


    /**
     * 组装考勤记录对象
     *
     * @param kqinfo
     * @return
     */
    private List<Kqjl> assembleKqjl(String[] kqinfo) {
        try {
            List<Kqjl> list = Lists.newArrayList();
            for (int i = 0; i < kqinfo.length; i++) {
                Kqjl kqjl = new Kqjl();
                kqjl.setId(IdGen.uuid());
                String[] info = kqinfo[i].split(",");
                int row = kckqjlDao.selectRdateByNum(info[0], info[3]);
                if (row <= 0) {
                    kqjl.setNum(info[0]);
                    switch (info[1]) {
                        case "仅指纹":
                            kqjl.setVaspect("0");
                            break;
                        default:
                            kqjl.setVaspect("0");
                            break;
                    }
                    kqjl.setInoutmode(info[2]);
                    kqjl.setRdate(info[3]);
                    kqjl.setAddress(info[5]);
                    list.add(kqjl);
                }
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}